const { chapter_opened, chapterModel, openedModel, courseModel, workTeaModel } = require('../../model');
const { getResultToObjectComplete } = require('../../services/utils');

module.exports = {
  list: async (req,res) => {
    const { org, id } = req.decode;
    const { series } = req.params;
    const chap_attr = ['id','order', 'name', 'page_url', 'map_url', 'points'];
    const chap_where = { series: series, org: org};

    try {
      const chapters = await chapterModel.findByFilter(chap_attr,chap_where);
      const opened_list = await chapter_opened.findByFilter(['chapter_id', 'learn_state'],{stu_id: id});
      if (!chapters)
        return res.send({status: 0, data: []});

      let hash = [];
      for (const open of opened_list) {
        hash[open.chapter_id] = open.learn_state}
      for (const chap of chapters) {
        hash[chap.id] ? chap.learn_state = hash[chap.id] : chap.learn_state = 0}

      return res.send({
        status: 0,
        data: chapters
      })
    } catch (e) { console.log(e)}
  },
  opened_list: async (req, res) => {
    const { chapter_id } = req.params;
    const { id, org } = req.decode;
    const course_attr = ['id', 'order', 'name', 'description', 'work_id', 'type'];

    try {
      const courses_list = await courseModel.findByFilter(course_attr,{ org: org, chapter: chapter_id });
      const opened_list = await openedModel.findByRelation(['work_id', 'course_id'], { stu_id: id }, {
        model: workTeaModel.getModel(), attributes: ['pageURL']});
      const opened_work_list = getResultToObjectComplete(opened_list, 'works_teach', ['pageURL']);

      let hash = [];
      for (const open of opened_work_list) {
        hash[open.course_id] = open;}
      for (const course of courses_list) {
        if (hash[course.id]) {
          if (hash[course.id].work_id === course.work_id) {
            course.lock_state = 2
          } else {
            course.lock_state = 3;
            course.work_id = hash[course.id].work_id
          }
          course.pageURL = hash[course.id].pageURL;
        } else {
          course.lock_state = 1;
        }
      }
      return res.send({status: 0, data: courses_list})

    } catch (e) {console.log(e)}

  }
};
